import math
f1 = open ('D:\\206s\\v1d.csv','r')
f2 = open ('D:\\206s\\v3d.csv','r')
f3 = open ('D:\\206s\\resd.txt','a+')
list1=[]  #tracker x y
list2=[]  #tracker y

list3=[]  #tracker x
list4=[]  #tracker y
listdistance=[]
listdistance2=[]
listdistance3=[]

finallist=[]
finallist2=[]
for line1 in f1:
    if line1.split(',')[2]=='1':
        list1.append(line1.split(',')[3])
        list1.append(line1.split(',')[4].replace('\n',''))
        list2.append(list1)
        list1=[]

for line2 in f2:
    list3.append(line2.split(',')[2])
    list3.append(line2.split(',')[3].replace('\n', ''))
    list4.append(list3)
    list3=[]


for i in range(len(list4)):
    olddistance = 100000
    for j in range(len(list2)):
        x1 = float(list4[i][0])*100
        x2 = float(list2[j][0])*100
        y1 = float(list4[i][1])*100
        y2 = float(list2[j][1])*100
        d1 = x1 - x2
        d2 = y1 - y2
        distance1 = math.sqrt(d1*d1+d2*d2)*1000
        if distance1 < olddistance:
            olddistance = distance1
            listdistance.append(i)
            listdistance.append(j)



    #print 'site is ' + list4[i][0] + '  ' + list4[i][1]
    listdistance2.append(listdistance[-2])
    listdistance2.append(listdistance[-1])
    listdistance=[]
    listdistance3.append(listdistance2)
    listdistance2=[]

for disi in range(len(listdistance3)):
    print listdistance3[disi][0]
    xx1=float(list4[listdistance3[disi][0]][0])*100000
    yy1=float(list4[listdistance3[disi][0]][1])*100000
    print int(listdistance3[disi][1])+1
    if int(listdistance3[disi][1])+3 > len(list2):
        n = len(list2)
    else:
        n=int(listdistance3[disi][1])+3
    xx2=float(list2[n-1][0])*100000
    yy2=float(list2[n-1][1])*100000
    dd1=xx2-xx1
    dd2=yy2-yy1
    a1=dd1
    b1=dd2
    if a1 > 0 and b1 > 0:
        slope1 = 90.0 - math.atan(abs(b1 / a1)) * 180 / 3.14
    elif a1 > 0 and b1 < 0:
        slope1 = 90.0 + math.atan(abs(b1 / a1)) * 180 / 3.14
    elif a1 < 0 and b1 > 0:
        slope1 = 270.0 + math.atan(abs(b1 / a1)) * 180 / 3.14
    elif a1 < 0 and b1 < 0:
        slope1 = 270.0 - math.atan(abs(b1 / a1)) * 180 / 3.14

    print slope1
    finallist.append(listdistance3[disi][0])
    finallist.append(slope1)
    finallist2.append(finallist)
    finallist=[]




for fini in range(len(finallist2)):
    f3.write(str(int(finallist2[fini][0])+1) +'='+str(int(finallist2[fini][1]))+'\n')
f3.close()

